package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.dto.Result;
import com.demo.dto.ScrollResult;
import com.demo.dto.UserDTO;
import com.demo.entity.Blog;
import com.demo.entity.Follow;
import com.demo.entity.User;
import com.demo.mapper.BlogMapper;
import com.demo.service.IBlogService;
import com.demo.service.IFollowService;
import com.demo.service.IUserService;
import com.demo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.demo.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.demo.utils.RedisConstants.FEED_KEY;

@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;

    /**
     * 根据id查询帖子
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("帖子不存在");
        }
        //查询发布blog的用户
        User user = userService.getById(blog.getUserId());
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        //查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    //判断是否点过赞
    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null){
            //用户未登录情况 无需查询
            return;
        }
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//        blog.setIsLike(score != null);
        if (score != null) {
            blog.setIsLike(true);
        }else {
            blog.setIsLike(false);
        }
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + id;
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3.如果未点赞 可以点赞
//        if (BooleanUtil.isFalse(isMember)){
        //TODO score为null 说明没有这个value
        if (score == null){
            //3.1 数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                //3.2 保存用户信息到redis的set集合
//                stringRedisTemplate.opsForSet().add(key,userId.toString());
                //TODO 改为可排序的ZSet集合 点赞时间作为score排序
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
            //4.如果已经点赞过了
        }else {
            //4.1 数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                //4.2 删除redis中用户信息
//                stringRedisTemplate.opsForSet().remove(key,userId.toString());
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询前五名的点赞用户 排序方法:zrange key 0 4
        String key = BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (set == null || set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.查出其中的用户id
        List<Long> idList = set.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据id查询用户
//        for (Long uid : idList) {
//            User user = userService.getById(uid);
//            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//            return Result.ok(userDTO);
//        }
        //User类型转换成非敏感类型UserDTO
        //TODO listByIds查询数据库 where in语句会导致顺序变乱
        List<UserDTO> userDTOs = userService.listByIds(idList)
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        //4.返回
        return Result.ok(userDTOs);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //1.获取登录用户id
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        //2.保存帖子信息
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("发布失败");
        }
        //3.查询作者的所有粉丝 follow表中 follow_user_id为当前作者的用户的id
        List<Follow> follows = followService.query().eq("follow_user_id", userId).list();
        //4.推送笔记给所有粉丝
        for (Follow follow : follows) {
            //获取粉丝id
            Long uid = follow.getUserId();
            //推送
            String key = FEED_KEY + uid;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1，获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //3.解析数据，blogId,minTime（时间戳）,offset偏移量
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int offs = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取id
            ids.add(Long.valueOf(typedTuple.getValue()));
            //获取分数
            long time = typedTuple.getScore().longValue();
            if (time == minTime){
                offs++;
            }else {
                minTime = time;
                offs = 1;
            }
        }
        //4.根据blogId查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id",ids).last("ORDER BY FIELD(id,"+ idStr +")").list();

        for (Blog blog : blogs) {
            //查询发布blog的用户
            User user = userService.getById(blog.getUserId());
            blog.setIcon(user.getIcon());
            blog.setName(user.getNickName());
            //查询blog是否被点赞
            isBlogLiked(blog);
        }
        //5.封装返回
        ScrollResult r = new ScrollResult();
        r.setMinTime(minTime);
        r.setOffset(offs);
        r.setList(blogs);
        return Result.ok(r);
    }
}
